var doc = app.activeDocument;
var artboards = doc.artboards;
var isRGBSpace = _getColorSpace() === 'RGB'

// drawAllArtboardBackground('bg-color', isRGBSpace ? [40,90,255] : [90, 55, 0, 0]) 
drawCurrArtboardBackground('bg-color', artboards[artboards.getActiveArtboardIndex()].artboardRect, isRGBSpace ? [40,90,255] : [90, 55, 0, 0])

function drawAllArtboardBackground(layerName, color) {
    for (var i = 0; i < artboards.length; i++) {
        var rect = artboards[i].artboardRect
        drawCurrArtboardBackground(layerName, rect, color)
    }
}

function drawCurrArtboardBackground(layerName, currRect, color) {
    var rect1 = _getArtboardSize(currRect)
    var layer = _getLayer(layerName)
    var bgRect = app.activeDocument.pathItems.rectangle(rect1.y, rect1.x, rect1.width, rect1.height);
    // var bgRect = layer.pathItems.rectangle(rect1.y, rect1.x, rect1.width, rect1.height);
    bgRect.fillColor = isRGBSpace ? _genRgbColor(color) : _genCmykColor(color) ;
    bgRect.stroked = false;
    // layer.locked = true;
}

function _getLayer(name) {
    var docRef = app.activeDocument
    var countOfLayers = docRef.layers.length;
    var layer = null;
    if (countOfLayers > 1) {
        for(var i =0; i < countOfLayers; i++) {
            if(docRef.layers[i].name === name) {
                layer = docRef.layers[i];
                layer.locked = false;
                layer.zOrder(ZOrderMethod.SENDTOBACK);
            }
        }
    } else {
        layer =  app.activeDocument.layers.add();
        layer.name = 'bg-color'
        layer.zOrder(ZOrderMethod.SENDTOBACK);
        return layer;
        
    }
    return layer;
}

function _getArtboardSize(rectObj) {
    var rect = rectObj.toString().split(',')
    var x1 = +rect[0]
    var y1 = +rect[1]
    var x2 = +rect[2]
    var y2 = +rect[3]
    var rectangle = {
        y: y1,
        x: x1,
        width: Math.abs(x2 - x1),
        height: Math.abs(y2 - y1)
    }
    return rectangle
}

function _getColorSpace() {
    return app.activeDocument.documentColorSpace == DocumentColorSpace.CMYK ? 'CMYK' : 'RGB'
}

function _genRgbColor(color) {
    var newRGBColor = new RGBColor();
    newRGBColor.red = color[0];
    newRGBColor.green = color[1];
    newRGBColor.blue = color[2];
    return newRGBColor
}

function _genCmykColor(color) {
    var newCMYKColor = new CMYKColor();
    newCMYKColor.cyan = color[0];
    newCMYKColor.magenta = color[1];
    newCMYKColor.yellow = color[2];
    newCMYKColor.black = color[3];
    return newCMYKColor
}


